package dao;

import java.util.List;

import hbt.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import negocio.Plato;

public class PlatoDAO 
{
	private static PlatoDAO instancia = null;
	private static SessionFactory sf = null;
	private Session session = null;
	
	public static PlatoDAO getInstancia()
	{
		if(instancia == null)
		{
			sf = HibernateUtil.getSessionFactory();
			instancia = new PlatoDAO();
		} 
		return instancia;
	}
	
	private Session getSession()
	{
		if(session == null || !session.isOpen())
			session = sf.openSession();
		return session;
	}
	
	public void closeSession()
	{
		if (session.isOpen()) session.close();
	}
	
	public void persist(Object o)
	{
		Session s=getSession();
		s.beginTransaction();
		s.persist(o);
		s.flush();
		s.getTransaction().commit();
	}
	
	public void delete(Object o)
	{
		Session s=getSession();
		s.beginTransaction();
		s.delete(o);
		s.flush();
		s.getTransaction().commit();
	}
	
	public void update(Object o)
	{
		Session s=getSession();
		s.beginTransaction();
		s.update(o);
		s.flush();
		s.getTransaction().commit();
	}

	public Plato buscarPlato(String nombres)
	{
		Session s=getSession();
		s.beginTransaction();
		Plato platos = (Plato) s.createQuery(
				"from Plato " +
				"where nombre in(:nombres)")
				.setParameter("nombres", nombres).uniqueResult();
		s.flush();
		s.getTransaction().commit();
		return platos;
	}

	@SuppressWarnings("unchecked")
	public List<Plato> getPlatos()
	{
		Session s=getSession();
		s.beginTransaction();
		List<Plato> platos = s.createQuery("from Plato").list();
		s.flush();
		s.getTransaction().commit();
		closeSession();
		return platos;
	}
	
	public Plato buscarPlato(int id)
	{
		Session s=getSession();
		Plato platos =  (Plato) s.get(Plato.class, new Integer(id));
		closeSession();
		return platos;
	}
}